import React from 'react';
import { Form, Row, Col, Input, Button, Tooltip } from 'antd';
import { DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons';
import _ from 'lodash';
import moment from 'moment';
import { useTranslation } from 'react-i18next';
import TimeRangePicker, { isMathString } from '@/components/TimeRangePicker';
import AdvancedSettings from '@/plugins/TDengine/components/AdvancedSettings';
import Collapse, { Panel } from '@/pages/dashboard/Editor/Components/Collapse';
import getFirstUnusedLetter from '@/pages/dashboard/Renderer/utils/getFirstUnusedLetter';
import { replaceExpressionVars } from '@/pages/dashboard/VariableConfig/constant';
import SqlTemplates from '../components/SqlTemplates';
import { MetaModal } from '../components/Meta';

const alphabet = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('');

export default function TDengineQueryBuilder({ chartForm, variableConfig, dashboardId }) {
  const { t } = useTranslation('dashboard');

  return (
    <Form.List name='targets' data-oid='grnbv0r'>
      {(fields, { add, remove }, { errors }) => {
        return (
          <>
            <Collapse data-oid='oh3rw9j'>
              {_.map(fields, (field, index) => {
                return (
                  <Panel
                    header={
                      <Form.Item noStyle shouldUpdate data-oid='clpk8r7'>
                        {({ getFieldValue }) => {
                          return getFieldValue(['targets', field.name, 'refId']) || alphabet[index];
                        }}
                      </Form.Item>
                    }
                    key={field.key}
                    extra={
                      <div data-oid='e4qn8jz'>
                        {fields.length > 1 ? (
                          <DeleteOutlined
                            style={{ marginLeft: 10 }}
                            onClick={() => {
                              remove(field.name);
                            }}
                            data-oid='jfbdrtj'
                          />
                        ) : null}
                      </div>
                    }
                    data-oid='9pj0_2w'
                  >
                    <Form.Item noStyle {...field} name={[field.name, 'refId']} data-oid='lvro_ns'>
                      <div data-oid='-elr9i1' />
                    </Form.Item>
                    <Row gutter={10} data-oid='q1abv7i'>
                      <Col flex='auto' data-oid='n_o1yvq'>
                        <Form.Item
                          label={
                            <span data-oid='h-p_bne'>
                              查询条件{' '}
                              <Tooltip
                                title={
                                  <span data-oid='o9dpqds'>
                                    TDengine 查询语法可参考
                                    <a target='_blank' href='https://docs.taosdata.com/basic/query/' data-oid='ipx74j-'>
                                      官方文档
                                    </a>
                                  </span>
                                }
                                data-oid='zbgreql'
                              >
                                <InfoCircleOutlined data-oid='0nqj_15' />
                              </Tooltip>
                            </span>
                          }
                          {...field}
                          name={[field.name, 'query', 'query']}
                          validateTrigger={['onBlur']}
                          rules={[
                            {
                              required: true,
                              message: t('db_tdengine:query.query_msg'),
                            },
                          ]}
                          style={{ flex: 1 }}
                          data-oid='kn_b441'
                        >
                          <Input data-oid='fhg7x1.' />
                        </Form.Item>
                      </Col>
                      <Col flex='92px' data-oid='5d6srxl'>
                        <div style={{ marginTop: 27 }} data-oid='lf1c963'>
                          <SqlTemplates
                            onSelect={(sql) => {
                              const targets = _.cloneDeep(chartForm.getFieldValue('targets'));
                              _.set(targets, [field.name, 'query', 'query'], sql);
                              chartForm.setFieldsValue({
                                targets,
                              });
                            }}
                            data-oid='bk4zqh7'
                          />
                        </div>
                      </Col>
                      <Col flex='62px' data-oid='4.zbwl4'>
                        <div style={{ marginTop: 27 }} data-oid='pm6ugwn'>
                          <Form.Item shouldUpdate={(prevValues, curValues) => _.isEqual(prevValues.datasourceValue, curValues.datasourceValue)} noStyle data-oid='-d_3j68'>
                            {({ getFieldValue }) => {
                              let datasourceValue = getFieldValue('datasourceValue');
                              datasourceValue = variableConfig ? replaceExpressionVars(datasourceValue, variableConfig, variableConfig.length, dashboardId) : datasourceValue;
                              return (
                                <MetaModal
                                  datasourceValue={datasourceValue}
                                  onTreeNodeClick={(nodeData) => {
                                    const targets = _.cloneDeep(chartForm.getFieldValue('targets'));
                                    _.set(targets, [field.name, 'query', 'query'], `select * from ${nodeData.database}.${nodeData.table} where _ts >= $from and _ts < $to`);
                                    if (nodeData.levelType === 'field') {
                                      _.set(targets, [field.name, 'query', 'keys'], {
                                        ...(targets?.[field.name]?.query?.keys || {}),
                                        metricKey: [nodeData.field],
                                      });
                                    }
                                    chartForm.setFieldsValue({
                                      targets,
                                    });
                                  }}
                                  data-oid='gor_ua-'
                                />
                              );
                            }}
                          </Form.Item>
                        </div>
                      </Col>
                    </Row>
                    <Row gutter={10} data-oid='dm_rlae'>
                      <Col flex='auto' data-oid='zuwl_x5'>
                        <Form.Item
                          label='Legend'
                          {...field}
                          name={[field.name, 'legend']}
                          tooltip={{
                            getPopupContainer: () => document.body,
                            title: t('dashboard:query.legendTip', {
                              interpolation: { skipOnVariables: true },
                            }),
                          }}
                          data-oid='1pb20hb'
                        >
                          <Input data-oid='2h8wvgb' />
                        </Form.Item>
                      </Col>
                      <Col flex='100px' data-oid='-:h1p06'>
                        <Form.Item
                          label={t('query.time')}
                          {...field}
                          name={[field.name, 'time']}
                          tooltip={{
                            getPopupContainer: () => document.body,
                            title: t('query.time_tip'),
                          }}
                          normalize={(val) => {
                            return {
                              start: isMathString(val.start) ? val.start : moment(val.start).format('YYYY-MM-DD HH:mm:ss'),
                              end: isMathString(val.end) ? val.end : moment(val.end).format('YYYY-MM-DD HH:mm:ss'),
                            };
                          }}
                          data-oid='c011dkn'
                        >
                          <TimeRangePicker
                            dateFormat='YYYY-MM-DD HH:mm:ss'
                            allowClear
                            onClear={() => {
                              const targets = chartForm.getFieldValue('targets');
                              const targetsClone = _.cloneDeep(targets);
                              _.set(targetsClone, [field.name, 'time'], undefined);
                              chartForm.setFieldsValue({
                                targets: targetsClone,
                              });
                            }}
                            data-oid='gl2ccp3'
                          />
                        </Form.Item>
                      </Col>
                    </Row>

                    <AdvancedSettings mode='graph' span={8} prefixField={field} prefixName={[field.name, 'query']} data-oid='zpx-4pc' />
                  </Panel>
                );
              })}

              <Form.ErrorList errors={errors} data-oid='t.l:3da' />
            </Collapse>
            <Button
              style={{ width: '100%', marginTop: 10 }}
              onClick={() => {
                add({ expr: '', refId: getFirstUnusedLetter(_.map(chartForm.getFieldValue('targets'), 'refId')) });
              }}
              data-oid='8-bgdpq'
            >
              + add query
            </Button>
          </>
        );
      }}
    </Form.List>
  );
}
